package top.mindse.office2pdf.handler;

import com.jacob.activeX.ActiveXComponent;
import com.jacob.com.Dispatch;
import com.jacob.com.Variant;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * .xls(x) 转换
 */
public class ExcelHandler {
    private static final Logger logger = LoggerFactory.getLogger(ExcelHandler.class);

    public static void toPdf(String src, String tar) {
        ActiveXComponent app = null;
        Dispatch doc = null;
        try {
            app = new ActiveXComponent("Excel.Application");
            app.setProperty("Visible", new Variant(false));
            app.setProperty("AutomationSecurity", new Variant(3));
            Dispatch docs = app.getProperty("Workbooks").toDispatch();
            doc = Dispatch.call(docs, "Open",
                    src, Boolean.FALSE, Boolean.TRUE)
                    .toDispatch();
            Dispatch.call(doc, "ExportAsFixedFormat",
                    0, tar);
        } catch (Throwable t) {
            logger.error(".xls(x)转PDF异常：转换异常", t);
        } finally {
            if (doc != null) {
                try {
                    Dispatch.call(doc, "Close", Boolean.FALSE);
                } catch (Throwable t) {
                    logger.error(".xls(x)转PDF异常：文件未正常关闭", t);
                }
            }
            if (app != null) {
                try {
                    app.invoke("Quit");
                    app.safeRelease();
                } catch (Throwable t) {
                    logger.error(".xls(x)转PDF异常：应用未退出", t);
                }
            }
        }
    }
}
